搜索 K
Appearance
博客正在加载中...
Appearance
搭建好了环境,接下来我们就配置下事务
配置事务管理器
配置事务的通知,此时我们需要导入事务的约束,也就是 tx 名称空间和约束,同时也需要 aop 的。
然后使用 tx: advice 标签配置事务通知。属性:id 给事务通知起一个唯一标识,transaction-manager:给事务通知提供一个事务管理器引用
配置 AOP 中的通用切入点表达式
建立事务通知和切入点表达式的对应关系
配置事务的属性:是在事务的通知 tx: advice 标签的内部
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 注入数据源 -->
<property name="dataSource" ref="dataSource"/>
</bean>需要导入事务的约束,也就是 tx 名称空间和约束,我们可以从文档中查找:

搜索 xmlns: tx,搜索内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 配置事务切入点 -->
<aop:config>
<aop:pointcut id="pt1" expression="execution(* com.peterjxl.service.impl.*.*(..))"/>
</aop:config>也就是配置在 AOP 中,配置事务对象
<!-- 配置事务切入点 -->
<aop:config>
<aop:pointcut id="pt1" expression="execution(* com.peterjxl.service.impl.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"/>
</aop:config>先使用 <tx:advice> 标签配置事务通知。标签属性:id 用于给事务通知起一个唯一标识,transaction-manager 用于给事务通知提供一个事务管理器引用
然后在 <tx:advice> 标签的内部配置属性,name 属性就是方法名
<!-- 配置事务通知 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="transfer" />
</tx:attributes>
</tx:advice>除了 name 属性,还有:
name 属性可以配置通配符:星号表示全部都使用事务
<tx:method name="*" />也可以配置 find 开头的方法不使用事务:
<tx:method name="*" />
<tx:method name="find*" propagation="SUPPORTS" read-only="true" />由于下面一行的配置更具体,因此下面的配置优先级更高,并不会被上面一行的配置覆盖
至此,事务控制就完成了
我们可以测试下,可以试试运行,可以看到有没异常都能正常处理。
本项目已将源码上传到 GitHub 和 Gitee 上。并且创建了分支 demo18,读者可以通过切换分支来查看本文的示例代码